package com.example.fence.entity;

import com.example.fence.mqtt.MqttCallBackHandle;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;
import com.example.fence.config.CommonConnectionConfig;


/**
 * 消息推送客户端
 */
@Component
@Slf4j
public class MyMqttClient {
    //客户端唯一ID
    private static final String clientid = MqttClient.generateClientId();

    public static MqttClient createMqtt() {
        MqttClient client = null;

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        //断开之后自动重联
        connectOptions.setAutomaticReconnect(true);
        //设置会话心跳时间 代理和客户端在不发送消息的情况下可以忍受的最长时间
        connectOptions.setKeepAliveInterval(CommonConnectionConfig.KEEP_ALIVE);
        //不建立持久会话
        connectOptions.setCleanSession(true);
        //同时发送消息的最大数量
        connectOptions.setMaxInflight(1000);
        //用户名
        connectOptions.setUserName(CommonConnectionConfig.USER_NAME);
        //密码
        connectOptions.setPassword(String.valueOf(CommonConnectionConfig.PASSWORD).toCharArray());
        try {
            client = new MqttClient(CommonConnectionConfig.HOST, clientid, new MemoryPersistence());
            //MQTT连接
            client.connect(connectOptions);
            //消息回调
            client.setCallback(new MqttCallBackHandle(client));
        } catch (MqttException e) {
            log.error("建立MQTT服务器消息异常： "+CommonConnectionConfig.HOST);
        }
        return client;

    }
    public static MqttClient createMqttForTB(String IMEI) {
        MqttClient client = null;

        MqttConnectOptions connectOptions = new MqttConnectOptions();
//        //断开之后自动重联
//        connectOptions.setAutomaticReconnect(true);
        //设置会话心跳时间 代理和客户端在不发送消息的情况下可以忍受的最长时间
        connectOptions.setKeepAliveInterval(CommonConnectionConfig.KEEP_ALIVE);
        //不建立持久会话
        connectOptions.setCleanSession(true);
        //用户名
        connectOptions.setUserName(IMEI);
        try {
            client = new MqttClient(CommonConnectionConfig.TBHOST, clientid, new MemoryPersistence());
            //MQTT连接
            client.connect(connectOptions);
            //消息回调
            client.setCallback(new MqttCallBackHandle(client));
        } catch (MqttException e) {
            log.error("向TB发送消息异常： "+IMEI+"TBHOST: "+CommonConnectionConfig.TBHOST);
        }
        return client;

    }





    /**
     * 消息推送
     * @param message 消息内容
     * @param topic   发送的主题
     */
    public static void publishMessage(String message, String topic, MqttClient mqttClient) {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(CommonConnectionConfig.QOS_1);
        mqttMessage.setPayload(message.getBytes());

        try {
            mqttClient.publish(topic, mqttMessage);
            //System.out.println("MQTT客户端:" + clientid + "向"+topic+"发送消息:{}" + message);
            log.info("MQTT客户端:" + clientid + "向"+topic+"发送消息:{}" + message);
        } catch (MqttException e) {
            log.error("MQTT消息推送失败");
            e.printStackTrace();
        }
    }


    public static void publishMessageHex(String message, String topic, MqttClient mqttClient) {
        byte[] data = new byte[message.length() / 2];
        for (int i = 0; i < data.length; i++) {
            int index = i * 2;
            int j = Integer.parseInt(message.substring(index, index + 2), 16);
            data[i] = (byte) j;
        }
        MqttMessage mqttMessage = new MqttMessage(data);
        mqttMessage.setQos(CommonConnectionConfig.QOS_1);
        // mqttMessage.setPayload(message.getBytes());

        try {
            mqttClient.publish(topic, mqttMessage);
           log.info("MQTT客户端:" + clientid + "向"+topic+"发送消息:{}" + message);
        } catch (MqttException e) {
            log.error("MQTT消息推送失败");
            e.printStackTrace();
        }
    }
}
